
//数据库
const db = require('../db/index')

//获取角色列表
const getRoleList = (req, res) => {
    let sql = 'select * from sp_role where role_del=0'
    db.query(sql, (err, result) => {
        if (err) return res.sendErr(err)
        if (result.length === 0) return es.sendErr("角色列表为空!")
        //成功
        res.send({
            status: 200,
            message: "获取角色列表成功!",
            data: result
        })
    })
}

//权限列表(全部)
let getLevel1 = (res) => {
    let sql = 'select ps_id,ps_name,ps_pid from sp_permission where ps_level="1"'
    return new Promise((resolve, reject) => {
        db.query(sql, (err, result) => {
            if (err) return res.sendErr(err)
            if (result.length === 0) return res.sendErr("查找权限列表失败!")
            resolve(result)
        })
    })
}
let getLevel1_2 = (res, result1) => {
    let sql = 'select ps_id,ps_name,ps_pid from sp_permission where ps_level="2" and ps_pid=?'
    return new Promise((resolve, reject) => {
        Object.keys(result1).forEach((key, index) => {
            db.query(sql, result1[key].ps_id, (err, result) => {
                if (err) return res.sendErr(err)  //长度为0不算错误
                result1[key].children = result

                //最后的
                if (index === result1.length - 1) {
                    // console.log(result1);
                    resolve(result1)
                }
            })
        });
    })
}
let getLevel0 = (res) => {
    let sql = 'select ps_id,ps_name,ps_pid from sp_permission where ps_level="0"'
    return new Promise((resolve, reject) => {
        db.query(sql, (err, result) => {
            if (err) return res.sendErr(err)
            if (result.length === 0) return res.sendErr("查找权限列表失败!")
            resolve(result)
        })
    })
}
let getLevel0_1_2 = (res, result0, result1_2) => {
    return new Promise((resolve, reject) => {
        Object.keys(result0).forEach((key, index) => {
            // console.log("====", result0[key].ps_id);
            result0[key].children = []
            result1_2.forEach(item => {
                if (item.ps_pid === result0[key].ps_id) {
                    // console.log("---", item.ps_id);
                    result0[key].children.push(item)
                    // 到了最后
                    if (index === result0.length - 1) {
                        resolve(result0)
                    }
                }
            })
        })
    })
}
const getPermissionList = async (req, res) => {
    let result1 = await getLevel1(res)
    let result1_2 = await getLevel1_2(res, result1)
    let result0 = await getLevel0(res)
    let result0_1_2 = await getLevel0_1_2(res, result0, result1_2)

    res.send({
        status: 200,
        message: "获取权限列表成功!",
        data: result0_1_2
    })
}

//添加角色
const addRole = (req, res) => {
    // console.log(req.body);
    let sql = 'insert into sp_role set ?'
    db.query(sql, req.body, (err, result) => {
        if (err) return sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("添加角色失败!")
        res.send({
            status: 200,
            message: "添加成功!"
        })
    })
}

//删除角色（逻辑删除）
const delRole = (req, res) => {
    let sql = 'update sp_role set role_del=1 where role_id=?'
    db.query(sql, req.body.role_id, (err, result) => {
        if (err) return res.sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("删除角色失败!")
        res.send({
            status: 200,
            message: "删除成功!"
        })
    })
}

//编辑角色消息
const editRole = (req, res) => {
    console.log(req.body);
    let sql = 'update sp_role set ? where role_id=?'
    db.query(sql, [req.body, req.body.role_id], (err, result) => {
        if (err) return res.sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("更改角色信息失败!")
        res.send({
            status: 200,
            message: "更改成功!"
        })
    })
}

//根据role_id得到对应的权限列表（ps_ids）
const getPermListById = (req, res) => {
    new Promise((resolve, reject) => {
        let sql = "select ps_id from sp_permission where ps_level='2'"
        db.query(sql, req.query.role_id, (err, result) => {
            if (err) return res.sendErr(err)
            // console.log("aaa", result);
            resolve(result)
        })
    }).then(level2List => {
        new Promise((resolve, reject) => {
            let sql = "select ps_ids from sp_role where role_id=?"
            db.query(sql, req.query.role_id, (err, result) => {
                if (err) return res.sendErr(err)
                if (result.length === 0) return res.sendErr("找不到该role_id的ps_ids")
                //转换为数组
                result[0].ps_ids = result[0].ps_ids.split(',')
                // console.log(result[0]);
                resolve(result[0])
            })
        }).then(response => {
            //response = result[0] ={ps_ids: ['1','2'....]}
            //level2List = 所有属于二级的id = [{ps_id:1},{ps_id:2}]
            permList = []
            response.ps_ids.forEach(item1 => {
                level2List.forEach(item2 => {
                    if (item1 === '' + item2.ps_id) {  //过滤
                        permList.push(item1)
                    }
                })
            })
            res.send({
                status: 200,
                message: "获取权限列表成功(role_id)!",
                data: permList, //上述将结果过滤后 剩下的只有第三级的标签
            })
        })
    })
}

//分配（更改）权限（ps_ids）
const dispatchPerm = (req, res) => {
    //把ps_ids换成字符串
    req.body.ps_ids = req.body.ps_ids.join(',')
    let sql = 'update sp_role set ps_ids=? where role_id=?'
    db.query(sql, [req.body.ps_ids, req.body.role_id], (err, result) => {
        if (err) return res.sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("权限分配失败!")
        res.send({
            status: 200,
            message: "分配权限成功!"
        })
    })
}

//根据role_id=>ps_ids=>获取角色具备的权限(expand展开权限)
let getLevel1ById = (res, select_str) => {
    let sql = `select ps_id,ps_name,ps_pid,ps_level from sp_permission where ps_level="1" and (${select_str})`
    return new Promise((resolve, reject) => {
        db.query(sql, (err, result) => {
            if (err) return res.sendErr(err)
            // 第二层找不到说明没有数据
            if (result.length === 0) return res.send({
                status: 200,
                message: "获取权限列表成功(为空)!",
                data: []
            })
            resolve(result)
        })
    })
}
let getLevel1_2ById = (res, result1, select_str) => {
    let sql = `select ps_id,ps_name,ps_pid,ps_level from sp_permission where ps_level="2" and ps_pid=? and (${select_str})`
    return new Promise((resolve, reject) => {
        let len = result1.length
        let delNum = 0
        result1.forEach((item, index) => {
            db.query(sql, item.ps_id, (err, result) => {
                if (err) return res.sendErr(err)  //长度为0不算错误
                if (result.length !== 0) {
                    result1[index - delNum].children = result
                } else { //为空这一行都删除（孩子为空 二级没有）
                    result1.splice(index - delNum, 1)
                    delNum++
                }
                //最后的
                if (index === len - 1) {
                    // console.log(result1);
                    resolve(result1)
                }
            })
        });
    })
}
let getLevel0ById = (res, select_str) => {
    let sql = `select ps_id,ps_name,ps_pid,ps_level from sp_permission where ps_level="0" and (${select_str})`
    return new Promise((resolve, reject) => {
        db.query(sql, (err, result) => {
            if (err) return res.sendErr(err)
            // 第一层都没有肯定是为空
            if (result.length === 0) return res.send({
                status: 200,
                message: "获取权限列表成功(为空)!",
                data: []
            })
            resolve(result)
        })
    })
}
let getLevel0_1_2ById = (res, result0, result1_2) => {
    // console.log(result0, result1_2);
    let len = result0.length
    let delNum = 0
    return new Promise((resolve, reject) => {
        result0.forEach((_, index1) => {
            let flag = true
            result0[index1 - delNum].children = []
            // console.log("====", index1);
            result1_2.forEach((item2, index2) => {
                // console.log("--------", index2);
                if (item2.ps_pid === result0[index1 - delNum].ps_id) {
                    result0[index1 - delNum].children.push(item2)
                    flag = false
                } else if (item2.ps_pid !== result0[index1 - delNum].ps_id && index2 === result1_2.length - 1 && flag) {
                    //没有孩子（一级没用的)
                    result0.splice(index1 - delNum, 1)
                    delNum++
                }
                // 到了最后
                if (index1 === len - 1) {
                    resolve(result0)
                }
            })
            //孩子直接为空那么 一级直接没用（直接返回是[]即可）
            if (result1_2.length === 0) {
                resolve(result1_2)
            }
        })
    })
}
const getExpPermListById = async (req, res) => {
    // console.log(req.query); //ps_ids: '101,104,105,116,117.....'
    //将得到的ps_ids拼接成条件语句 ps_id=101 or ps_id=104 or ...
    if (req.query.ps_ids != "") {
        let select_str = "ps_id=" + req.query.ps_ids.replace(/,/g, " or ps_id=");

        let result1 = await getLevel1ById(res, select_str);
        let result1_2 = await getLevel1_2ById(res, result1, select_str)
        let result0 = await getLevel0ById(res, select_str)
        var result0_1_2 = await getLevel0_1_2ById(res, result0, result1_2)
    }

    res.send({
        status: 200,
        message: "获取权限列表成功(role_id)!",
        data: result0_1_2
    })
}

//删除role_id对应的权限ps_ids
const delPermById = (req, res) => {
    //将权限
    req.body.ps_ids = req.body.ps_ids.join(',')
    console.log(req.body);
    let sql = 'update sp_role set ps_ids=? where role_id=?'
    db.query(sql, [req.body.ps_ids, req.body.role_id], (err, result) => {
        if (err) return res.sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("权限删除失败!")
        //成功
        res.send({
            status: 200,
            message: "权限删除成功!"
        })
    })
}

module.exports = {
    getRoleList,
    getPermissionList,
    addRole,
    delRole,
    editRole,
    getPermListById,
    dispatchPerm,
    getExpPermListById,
    delPermById
}